package com.songlanyun.modules.sharerecord.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.shareconfig.entity.SystemShareConfig;
import com.songlanyun.modules.shareconfig.service.SystemShareConfigService;
import com.songlanyun.modules.sharerecord.dao.SystemShareOpenRecordDao;
import com.songlanyun.modules.sharerecord.entity.SystemShareOpenRecord;
import com.songlanyun.modules.sharerecord.model.SystemShareOpenRecordDTO;
import com.songlanyun.modules.sharerecord.service.SystemShareOpenRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("systemShareOpenRecordService")
public class SystemShareOpenRecordServiceImpl extends ServiceImpl<SystemShareOpenRecordDao, SystemShareOpenRecord>
        implements SystemShareOpenRecordService {

    @Autowired
    private SystemShareConfigService systemShareConfigService;
    @Autowired
    private GoodsService goodsService;
    @Override
    public SystemShareOpenRecord create(SystemShareOpenRecord entity) {
        this.save(entity);
        return entity;
    }

    @Override
    public SystemShareOpenRecord modify(SystemShareOpenRecord entity) {
        this.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {


    }

    @Override
    public SystemShareOpenRecord add(SystemShareOpenRecordDTO dto) {
        SystemShareOpenRecord entity = new SystemShareOpenRecord();
        BeanUtil.copyPropertiesIgnoreNull(dto, entity);//克隆一份
        ValidatorUtils.validateEntity(entity);

        Goods goods = goodsService.getById(dto.getGoodsId(),false);
        //如果没有商品不用添加分享记录
        if(null == goods){
            return null;
        }

        SystemShareConfig systemShareConfig = systemShareConfigService.loadByShopId(goods.getShopId());
        //如果商家没有开通分享分成不用记录
        if(systemShareConfig==null || !systemShareConfig.getIsShare())
        {
            return null;
        }
        //如果商家没有开通app端的分享分成不用记录
        if(dto.getClient().equals("app") && !systemShareConfig.getIsAppShare())
        {
            return  null;
        }

        //如果商家没有开通applet端的分享分成不用记录
        if(dto.getClient().equals("applet") && !systemShareConfig.getIsAppletsShare())
        {
            return  null;
        }

        //如果打开自己的分享不记录
        if(dto.getUserId().equals(dto.getShareUserId()))
        {
            return null;
        }

        //如果下订单的会员，因分享人的分享给过
        SystemShareOpenRecord load = this.loadBy(dto.getUserId(),dto.getShareUserId(),dto.getGoodsId(),dto.getClient());
        //如果不存在相关记录，添加
        if(load == null) {
            entity.setShopId(goods.getShopId());
            entity.setOpenTime(new Date());
            entity.setLostTime(OrderConstant.getTomorrowAndDayTimestamp(System.currentTimeMillis(), systemShareConfig.getUserShareValidTime()));
            return this.create(entity);
        }
        else
        {
            //刷新相关记录的打开时间与失效时间
            load.setOpenTime(new Date());
            load.setLostTime(OrderConstant.getTomorrowAndDayTimestamp(System.currentTimeMillis(), systemShareConfig.getUserShareValidTime()));
            return this.modify(load);
        }
    }

    @Override
    public SystemShareOpenRecord loadBy(Long userId, Long shareUserId, Long goodsId,String client) {
        return this.getOne(new LambdaQueryWrapper<SystemShareOpenRecord>()
                .eq(SystemShareOpenRecord::getUserId,userId)
                .eq(SystemShareOpenRecord::getShareUserId,shareUserId)
                .eq(SystemShareOpenRecord::getGoodsId,goodsId)
                .eq(SystemShareOpenRecord::getClient,client)
                .last("limit 1")
        );
    }

    /**
     * 会员购买商品时间需要用到的查询,查询得到，就给分享人分成
     * @param userId
     * @param goodsId
     * @param client
     * @return
     */
    @Override
    public SystemShareOpenRecord loadBy(Long userId, Long goodsId, String client) {
        return this.getOne(new LambdaQueryWrapper<SystemShareOpenRecord>()
                .eq(SystemShareOpenRecord::getUserId,userId)
                .eq(SystemShareOpenRecord::getGoodsId,goodsId)
                .eq(SystemShareOpenRecord::getClient,client)
                .gt(SystemShareOpenRecord::getLostTime,System.currentTimeMillis())
                .orderByDesc(SystemShareOpenRecord::getOpenTime)
                .last("limit 1")
        );
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        return null;
    }


}